
package com.eshop.common.aspect;

import com.eshop.common.bean.LocalUser;
import com.eshop.logging.domain.Log;
import com.eshop.logging.service.LogService;
import com.eshop.utils.RequestHolder;
import com.eshop.utils.StringUtils;
import com.eshop.utils.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhonghui
 * @date 2018-11-24
 */
@Component
@Aspect
@Slf4j
public class AppLogAspect {

    private final LogService logService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    public AppLogAspect(LogService logService) {
        this.logService = logService;
    }

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.eshop.logging.aop.log.AppLog)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        //设置开始时间
        currentTime.set(System.currentTimeMillis());
        //如果下面这条原方法发生异常，则下面那一大段全部都执行不了
        result = joinPoint.proceed();
        //算出运行时间，然后存到Log对象里面
        Log log = new Log("INFO",System.currentTimeMillis() - currentTime.get());
        //记得Remove
        currentTime.remove();
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        //保存到log表里面，用户名，IP地址，方法名，log日志(运行时间)，uid
        logService.saveApp(getUsername(),
                StringUtils.getIp(RequestHolder.getHttpServletRequest()),joinPoint,
                log,getUid());
        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        //发生异常后，从原方法直接跳到这段，因为在环绕通知里面已经set过currentTime了，所以这里直接取出来
        Log log = new Log("ERROR",System.currentTimeMillis() - currentTime.get());
        //还是一样的，记得remove()
        currentTime.remove();
        //设置日志的详细报错信息
        log.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes());
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        //同样保存到log表里面
        logService.save(getUsername(),
                StringUtils.getIp(RequestHolder.getHttpServletRequest()),
                (ProceedingJoinPoint)joinPoint, log,getUid());
    }

    public String getUsername() {
        try {
            return LocalUser.getUser().getUsername();
        }catch (Exception e){
            return "";
        }
    }

    public Long getUid(){
        try {
            return LocalUser.getUser().getUid();
        }catch (Exception e){
            return 0L;
        }
    }
}
